package com.example.jf.jfapp;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jf.jfapp.bean.request.UserRequest;
import com.example.jf.jfapp.bean.response.ErrorResponse;
import com.example.jf.jfapp.utils.Constant;
import com.example.jf.jfapp.utils.RequestUtils;
import com.google.gson.Gson;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by jf on 2017/7/26.
 */

public class RegisterActivity extends AppCompatActivity {
    @BindView(R.id.logo)
    ImageView logo;
    @BindView(R.id.user_name)
    EditText userName;
    @BindView(R.id.user_password)
    EditText userPassword;
    @BindView(R.id.ensure_pass)
    EditText ensurePass;
    @BindView(R.id.register)
    Button register;
    @BindView(R.id.tv_login)
    TextView tvLogin;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
    }
    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    public void signup() {
        if (!validate()) {
            return;
        }
        register.setEnabled(false);

        final ProgressDialog progressDialog = new ProgressDialog(RegisterActivity.this);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("正在注册，请稍后...");
        progressDialog.show();

        String name = userName.getText().toString();
        String password = userPassword.getText().toString();
        UserRequest userRequest = new UserRequest(name, password);
        Request request = RequestUtils.requestPOST(userRequest, Constant.URL.USER_REGIST);
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String result = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.dismiss();
                        if (response.code() == 201) {//
                            Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            ErrorResponse errorResponse = new Gson().fromJson(result, ErrorResponse.class);
                            if (errorResponse.getCode() == 202) {
                                Toast.makeText(RegisterActivity.this, "用户名已经存在", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
                            }
                            register.setEnabled(true);
                        }
                    }
                });
            }
        });

    }

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    public boolean validate() {
        boolean valid = true;

        String name = userName.getText().toString();
        String password = userPassword.getText().toString();
        String reEnterPassword = ensurePass.getText().toString();

        if (name.isEmpty() || name.length() < 3) {
            userName.setError("用户名必须大于三位");
            valid = false;
        } else {
            userName.setError(null);
        }


        if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
            userPassword.setError("长度必须大于4，小于10");
            valid = false;
        } else {
            userPassword.setError(null);
        }

        if (reEnterPassword.isEmpty() || reEnterPassword.length() < 4 || reEnterPassword.length() > 10 || !(reEnterPassword.equals(password))) {
            ensurePass.setError("两次密码不一致");
            valid = false;
        } else {
            ensurePass.setError(null);
        }

        return valid;
    }

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @OnClick({R.id.register, R.id.tv_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.register:
                signup();
                break;
            case R.id.tv_login:
                Intent  intent = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                break;
        }
    }
}
